package org.example.buysystem.service;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.Good;
import org.example.buysystem.entity.GoodStandard;
import org.example.buysystem.entity.dto.GoodDto;
import org.example.buysystem.exception.ServiceException;
import org.example.buysystem.mapper.GoodMapper;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.buysystem.constants.RedisConstants.GOOD_TOKEN_KEY;
import static org.example.buysystem.constants.RedisConstants.GOOD_TOKEN_TTL;

@Service
public class GoodService extends ServiceImpl<GoodMapper, Good>{

    private final GoodMapper goodMapper;
    @Resource
    private RedisTemplate<String, Good> redisTemplate;

    public GoodService(GoodMapper goodMapper) {
        this.goodMapper = goodMapper;
    }


    public List<GoodDto> findAllGoods() {
        return goodMapper.findallGoods();

    }

    public Object getGoodsById(Long id) {
        String redisKey=GOOD_TOKEN_KEY+id;

        ValueOperations<String, Good> valueOperations = redisTemplate.opsForValue();

        Good redisGood = valueOperations.get(redisKey);

        if (redisGood != null) {
            redisTemplate.expire(redisKey, GOOD_TOKEN_TTL, TimeUnit.SECONDS);
            return redisGood;
        }

        LambdaQueryWrapper<Good> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Good::getId,id);
        queryWrapper.eq(Good::getIsDelete,false);

        Good dbGood = getOne(queryWrapper);
        if (dbGood != null) { //数据库有，则存入redis
            valueOperations.set(redisKey, dbGood);
            redisTemplate.expire(redisKey, GOOD_TOKEN_TTL, TimeUnit.MINUTES);
            return dbGood;
        }
        throw new ServiceException(Constants.NO_RESULT,"未查询到结果");
//        return null;
    }


    public Object getStandardById(Long id) {
        List<GoodStandard> standards=goodMapper.getStandardById(id);
        if (standards.size() == 0) {
            throw new ServiceException(Constants.NO_RESULT,"无规格信息");

        }
        String jsonString = JSON.toJSONString(standards);
        return jsonString;

    }

    public Object findGoodsByPage(Integer pageNum, Integer pageSize, String searchText, Integer categoryId) {
        LambdaQueryWrapper<Good> queryWrapper = new LambdaQueryWrapper<>();

        if(StrUtil.isNotBlank(searchText)){ //模糊查询
            queryWrapper.like(Good::getName,searchText).or().like(Good::getDescription,searchText)
                    .or().like(Good::getId,searchText);
        }
        if(categoryId!= null) {
            queryWrapper.eq(Good::getCategoryId, categoryId);
        }

        //排除已删除的商品
        queryWrapper.eq(Good::getIsDelete, false);
        IPage<Good> Page=this.page(new Page<>(pageNum,pageSize),queryWrapper);

        for(Good good:Page.getRecords()){
        good.setSaleMoney(getMinPrice(good.getId()));
        }

        return Page;
    }

    private BigDecimal getMinPrice(Long id) {

        return goodMapper.getMinPrice(id);
    }


    public boolean updateRecommend(Long id, Boolean recommend) {
        LambdaUpdateWrapper<Good> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Good::getId,id).set(Good::getRecommend,recommend);
        return update(queryWrapper);

    }

    public Object addGood(Good good) {
        if(good.getId()==null)
        {
            DateTimeFormatter df= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            good.setCreateTime(df.format(LocalDateTime.now()));
            goodMapper.insert(good);


        }else{
            saveOrUpdate(good);
            redisTemplate.delete(GOOD_TOKEN_KEY+good.getId());

        }
        return good;
    }

    public Object findPage(Integer pageNum, Integer pageSize, String searchText, Integer categoryId) {

        LambdaQueryWrapper<Good> queryWrapper = Wrappers.<Good>lambdaQuery().orderByDesc(Good::getId);

        if(StrUtil.isNotBlank(searchText)){
            queryWrapper.like(Good::getName,searchText).or().like(Good::getDescription,searchText)
                    .or().like(Good::getId,searchText);
        }

        if(categoryId!=null){
            queryWrapper.eq(Good::getCategoryId,categoryId);
        }

        queryWrapper.eq(Good::getIsDelete,false);
        IPage<Good> page=this.page(new Page<>(pageNum,pageSize),queryWrapper);

        IPage<GoodDto> goodDtoIPage=page.convert(good -> {
            GoodDto goodDto = new GoodDto();
            BeanUtil.copyProperties(good, goodDto);
            return goodDto;
        });
        for(GoodDto goodDto:goodDtoIPage.getRecords()){
            goodDto.setPrice(getMinPrice(goodDto.getId()));
        }
        return goodDtoIPage;
    }

    public void deleteGood(Long id) {
        redisTemplate.delete(GOOD_TOKEN_KEY+id);
        goodMapper.fakeDelete(id);

    }
}
